﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Grain.Crm.ExcelExtractor;
using Grain.Crm.ExcelExtractor.Input;

namespace Grain.Crm.DataMigrator.Infrastructure
{
    public class SheetContentRetriever : SheetContentRetrieverBase
    {
        public SheetContentRetriever(SheetDescription sheet, string entityName, EnumerableRowCollection<DataRow> data)
        {
            EntityName = entityName;
            SheetDescription = sheet;
            Data = data;
        }

        public override ImportPayload Retrieve()
        {
            var contentRow = GenerateContentRow(SheetDescription, Data, EntityName);
            var headerRow = GenerateHeaderRow(SheetDescription, EntityName);

            var result = new ImportPayload(EntityName, contentRow, headerRow, "");

            return result;
        }
    }

    public interface IContentRetriever
    {
        ImportPayload Retrieve();
    }

    public abstract class SheetContentRetrieverBase : IContentRetriever
    {
        public abstract ImportPayload Retrieve();

        public string EntityName { get; set; }
        public SheetDescription SheetDescription { get; set; }
        public EnumerableRowCollection<DataRow> Data { get; set; }

        protected string GenerateContentRow(SheetDescription sheetDescription, EnumerableRowCollection<DataRow> collection, string entityName)
        {
            var contentRowBuilder = new StringBuilder();
            int seq = 0;

            foreach (var description in sheetDescription.Descriptions)
            {
                if (description.IsSpecial || description.CrmEntity != entityName) continue;

                var value = XlsValueRetriever.GetValueByDescription(collection, description);

                if (seq > 0)
                    contentRowBuilder.Append(",");

                contentRowBuilder.Append(value);

                seq++;
            }

            return contentRowBuilder.ToString();
        }

        protected string GenerateHeaderRow(SheetDescription sheetDescription, string entityName)
        {
            var headerRowBuilder = new StringBuilder();

            foreach (var description in sheetDescription.Descriptions)
            {
                if (description.IsSpecial || description.CrmEntity != entityName) continue;

                if (headerRowBuilder.Length > 0)
                    headerRowBuilder.Append(",");
                headerRowBuilder.Append(description.CrmDisplayName);
            }

            return headerRowBuilder.ToString();
        }
    }

}
